package com.sportizz.sport.row;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sportizz.model.ImageLoader;
import com.sportizz.model.player_info;
import com.sportizz.sport.Br_custom_tweet_list;
import com.sportizz.sport.Custom_dialog_class;
import com.sportizz.sport.DatabaseAdapter;
import com.sportizz.sport.MainActivity;
import com.sportizz.sport.MainMenu;
import com.sportizz.sport.R;
import com.sportizz.sport.SubMenu;
import com.sportizz.sport.R.color;
import com.sportizz.sport.StartActivity;
import com.sportizz.sport.Utils;
import com.sportizz.sport.st_tweet_MainMenu;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;

public class new_Br_custom_team_list extends ArrayAdapter<player_info> {

	Activity context;
	ArrayList<String> sport_team_adp;
	HashMap<String, String> team_code;
	LayoutInflater lif;
	String[] code;
	String country_code;
	List<player_info> player_adp;
	private boolean bpress = false;
	public String response = null; 
	public Long ins1_c;
	public ProgressDialog pd;
	public WindowManager mWindowManager;

	StartActivity sa = new StartActivity();
	ImageLoader imgLoader;
	Context con;

	public new_Br_custom_team_list(Context _context, List<player_info> player_adp) {

		super(_context, R.layout.br_team_custom_follow, player_adp);
		
		context = (Activity) _context;

		this.con = _context;

		this.player_adp = player_adp;

		mWindowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);

		imgLoader = new ImageLoader(con.getApplicationContext());
	}

	static class ViewHolder {

		protected TextView br_set_team_name;
		protected Button br_set_team_follow;
		protected Button br_set_team_tweet;
		protected ImageView team_image;

//		public ViewHolder(TextView br_set_team_name, Button br_set_team_follow,
//				ImageView team_image, Button br_set_team_tweet) {
//
//			this.br_set_team_name = br_set_team_name;
//			this.br_set_team_follow = br_set_team_follow;
//			this.team_image = team_image;
//			this.br_set_team_tweet = br_set_team_tweet;
//		}
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		LayoutInflater inflator = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final ViewHolder viewHolder;

		if (convertView == null) {
			convertView = inflator.inflate(R.layout.br_team_custom_follow, null);
			viewHolder = new ViewHolder();
			
			viewHolder.br_set_team_name =(TextView) convertView
					.findViewById(R.id.br_set_team_name);
			viewHolder.br_set_team_follow =(Button) convertView
					.findViewById(R.id.br_set_team_follow);
			viewHolder.team_image =(ImageView) convertView
					.findViewById(R.id.br_set_image);
			viewHolder.br_set_team_tweet = (Button) convertView
					.findViewById(R.id.team_tweet);

			convertView.setTag(viewHolder);

		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}

		Typeface sport_font = Typeface.createFromAsset(con.getAssets(),
				"hel57.ttf");

		viewHolder.br_set_team_follow.setTag(player_adp.get(position).getplayerCode());

		viewHolder.br_set_team_tweet.setTag(player_adp.get(position).getplayerCode() + ":"
				+ player_adp.get(position).getPlayerName() + ":"
				+ player_adp.get(position).getsportCode());

		viewHolder.br_set_team_name.setText(player_adp.get(position).getPlayerName());

		viewHolder.br_set_team_name.setTypeface(sport_font);

		viewHolder.br_set_team_name.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

		Log.d("suraj", "player_adp.get(position).getPlayerName()="
				+ player_adp.get(position).getPlayerName());

		if (player_adp.get(position).getnational()
				.equals(player_adp.get(position).getss_club5())) {

			String player_code1 = "" + StartActivity.get_img_location
					+ "phone/country/" + player_adp.get(position).getnational()
					+ ".png";

			int loader = getImgLoader(player_adp.get(position).getsportCode());

			imgLoader.DisplayImage(player_code1, loader, viewHolder.team_image);

		} else {
			String player_code1 = "" + StartActivity.get_img_location
					+ "phone/" + player_adp.get(position).getsportCode() + "/"
					+ player_adp.get(position).getplayerCode() + ".png";

			int loader = getImgLoader(player_adp.get(position).getsportCode());

			imgLoader.DisplayImage(player_code1, loader, viewHolder.team_image);
		}
		

		
		viewHolder.br_set_team_follow.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				final DatabaseAdapter mDbHelper = new DatabaseAdapter(context);
				mDbHelper.open();

				StartActivity.foll_count = StartActivity.follow_count.getInt(
						"follow_count", 0);

				Log.e("suraj", "StartActivity.foll_count = "
						+ player_adp.get(position)
						.getPlayerName());

				// if (StartActivity.foll_count < StartActivity.limited_follow
				// .getInt("max_follow", 3)
				// && StartActivity.foll_count >= 0) {

				if (viewHolder.br_set_team_follow.getText().toString()
						.equalsIgnoreCase("FOLLOW")) {

					AsyncTask<Void, Void, Void> wait = new AsyncTask<Void, Void, Void>() {

						@Override
						protected void onPostExecute(Void result) {
							super.onPostExecute(result);
							pd.dismiss();

						}

						@Override
						protected void onPreExecute() {

							pd = ProgressDialog.show(context, "",
									"Following...", true);
							super.onPreExecute();
						}

						@Override
						protected Void doInBackground(Void... params) {
							try {
								String device_id = sa.GetDeviceID(context);

								String national = null;

								if (player_adp
										.get(position)
										.getnational()
										.equals(player_adp.get(position)
												.getss_club5())) {
									national = player_adp.get(position)
											.getnational();
								} else {
									national = player_adp.get(position)
											.getplayerCode();
								}

								ins1_c = mDbHelper
										.insert_follow_info(
												player_adp.get(position)
														.getplayerCode(),
												player_adp.get(position)
														.getPlayerName(),
												player_adp.get(position)
														.getsportCode(),
												player_adp.get(position)
														.getSportName(),
												national,
												player_adp.get(position)
														.getplayeris_team(),
												"P");

								response = Utils
										.getJSONString("http://sportizza.com/interface/ios_follow.php?dev_id="
												+ device_id
												+ "&iso_cd="
												+ country_code
												+ "&follow="
												+ player_adp.get(position)
														.getplayerCode()
												+ "&follow_cs=-1");
							} catch (Exception e) {

							}

							if (response != null || ins1_c != 0) {

								Thread t = new Thread(new Runnable() {
									public void run() {

										context.runOnUiThread(new Runnable() {
											public void run() {

												Toast.makeText(
														context.getApplicationContext(),
														"Added to I follow",
														Toast.LENGTH_SHORT)
														.show();
												Log.d("suraj",
														"follow success..");

												viewHolder.br_set_team_follow
														.setText("UNFOLLOW");

												MainActivity.playerAll
														.add(player_adp
																.get(position)
																.getplayerCode());

												Log.d("suraj",
														"PLAYER = "
																+ MainActivity.playerAll);

												StartActivity.foll_count++;

												SharedPreferences.Editor editor = StartActivity.follow_count
														.edit();
												editor.putInt(
														"follow_count",
														StartActivity.foll_count);
												editor.commit();
											}
										});
									}
								});
								t.start();

							} else {
								Toast.makeText(context.getApplicationContext(),
										"Error during follow",
										Toast.LENGTH_SHORT).show();
							}

							bpress = true;
							mDbHelper.close();

							return null;
						}

					};
					wait.execute();

				}
				// ///////////

				Log.d("suraj", "Team_code = " + viewHolder.br_set_team_follow.getTag()
						+ ":" + player_adp.get(position).getSportName() + ":"
						+ player_adp.get(position).getnational() + ":"
						+ player_adp.get(position).getss_club5() + ":"
						+ player_adp.get(position).getsportCode());

			}

		});

		viewHolder.br_set_team_tweet.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				final String[] data = { "PLAYERS", "TWEETS" };

				LayoutInflater layoutInflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View popupView = layoutInflater.inflate(
						R.layout.st_team_tweet_popup_main, null);
				final PopupWindow popupWindow = new PopupWindow(popupView,
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
						true);

				popupWindow.setOutsideTouchable(true);
				// //
				// popupWindow.setBackgroundDrawable (new BitmapDrawable());
				// popupWindow.setTouchable(true);
				// popupWindow.setFocusable(false);
				//
				LinearLayout rr = (LinearLayout) popupView
						.findViewById(R.id.op_li);
				rr.setOnTouchListener(new OnTouchListener() {

					@Override
					public boolean onTouch(View arg0, MotionEvent arg1) {

						popupWindow.dismiss();

						return false;
					}
				});

				final ListView listView = (ListView) popupView
						.findViewById(R.id.listView1);

				// listView.setAdapter(new
				// ArrayAdapter<String>(getApplicationContext(),
				// android.R.layout.simple_list_item_1,data));
				listView.setAdapter(new st_tweet_MainMenu(context, data));

				listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					public void onItemClick(AdapterView<?> parent, View v,
							final int position, long id) {

						// v.setBackgroundColor(color.da_gray);
						// Toast.makeText(context,"You Clicked : " +
						// br_set_team_tweet.getTag().toString()
						// ,Toast.LENGTH_SHORT).show();

						popupWindow.dismiss();

						final String[] br_tweet_str = viewHolder.br_set_team_tweet
								.getTag().toString().split(":");

						if (data[position].toString().equals("PLAYERS")) {

							LayoutInflater layoutInflater = (LayoutInflater) context
									.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
							View popupView = layoutInflater.inflate(
									R.layout.team_player_popup_main, null);
							final PopupWindow popupWindow = new PopupWindow(
									popupView, LayoutParams.WRAP_CONTENT,
									LayoutParams.WRAP_CONTENT, true);

							Button btn_close = (Button) popupView
									.findViewById(R.id.button_close);
							final ListView listView = (ListView) popupView
									.findViewById(R.id.listView_team_player);

							btn_close.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View arg0) {
									// TODO Auto-generated method stub
									popupWindow.dismiss();
								}
							});

							final ListView listView_team_player = (ListView) popupView
									.findViewById(R.id.listView_team_player);
							TextView txt_team_player = (TextView) popupView
									.findViewById(R.id.txt_team_player);
							final TextView empty_text = (TextView) popupView
									.findViewById(R.id.empty_text);

							txt_team_player.setText(br_tweet_str[1]
									+ "  PLAYERS");

							final List<String> data_sub_player = new ArrayList<String>();
							// listView.setAdapter(new
							// ArrayAdapter<String>(getApplicationContext(),
							// android.R.layout.simple_list_item_1,data));
							final ArrayAdapter<String> team_player = new ArrayAdapter<String>(
									context,
									android.R.layout.simple_list_item_1,
									data_sub_player);
							listView_team_player.setAdapter(team_player);

							AsyncTask<Void, Void, Void> wait1 = new AsyncTask<Void, Void, Void>() {

								@Override
								protected void onPostExecute(Void result) {
									// TODO Auto-generated method stub
									super.onPostExecute(result);
									pd.dismiss();

									team_player.notifyDataSetChanged();
								}

								@Override
								protected void onPreExecute() {
									pd = ProgressDialog.show(context, "",
											"Loading...", true);
									super.onPreExecute();
								}

								@Override
								protected Void doInBackground(Void... params) {

									String teamplayerlistjson = Utils
											.readJsonFeed(
													"http://sportizza.com/interface/ios_get_player_in_teams.php?club_code="
															+ br_tweet_str[0]
															+ "", context);

									if (teamplayerlistjson == null
											|| teamplayerlistjson
													.equals("null")) {

										Thread t = new Thread(new Runnable() {
											public void run() {
												context.runOnUiThread(new Runnable() {

													@Override
													public void run() {

														empty_text
																.setText("Information does not exist now. Please check back later");

														listView_team_player
																.setEmptyView(empty_text);

													}
												});

											}
										});
										t.start();
									} else {
										JSONArray array_teamplayer = null;
										try {
											array_teamplayer = new JSONArray(
													teamplayerlistjson);

											int array_len1 = array_teamplayer
													.length();

											for (int i = 0; i < array_len1; i++) {

												JSONObject JsonObject_sport = array_teamplayer
														.getJSONObject(i);

												String teamplayer_name = JsonObject_sport
														.getString("ss_player_name");

												data_sub_player
														.add(teamplayer_name);
											}

											// lv.setAdapter(null);
											// lv.setVisibility(View.VISIBLE);

										} catch (JSONException e) {
											e.printStackTrace();
										}
									}
									return null;
								}
							};
							wait1.execute();

							popupWindow.showAtLocation(viewHolder.br_set_team_tweet,
									Gravity.NO_GRAVITY, 0, 0);

						} else if (data[position].toString().equals("TWEETS")) {
							LayoutInflater layoutInflater = (LayoutInflater) context
									.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
							View popupView = layoutInflater.inflate(
									R.layout.team_player_popup_main, null);
							final PopupWindow popupWindow = new PopupWindow(
									popupView, LayoutParams.WRAP_CONTENT,
									LayoutParams.WRAP_CONTENT, true);

							Button btn_close = (Button) popupView
									.findViewById(R.id.button_close);
							final ListView listView = (ListView) popupView
									.findViewById(R.id.listView_team_player);

							btn_close.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View arg0) {
									// TODO Auto-generated method stub
									popupWindow.dismiss();
								}
							});

							final ListView listView_team_player = (ListView) popupView
									.findViewById(R.id.listView_team_player);
							TextView txt_team_player = (TextView) popupView
									.findViewById(R.id.txt_team_player);
							final TextView empty_text = (TextView) popupView
									.findViewById(R.id.empty_text);

							txt_team_player.setText(br_tweet_str[1]
									+ "  TWEETS");

							final HashMap<String, String> tweet_details = new HashMap<String, String>();
							//
							// sport_team_adp=new ArrayList<String>();

							final List<String> tweet_info = new ArrayList<String>();

							final Br_custom_tweet_list br_tweetlist = new Br_custom_tweet_list(
									context, tweet_info, tweet_details);

							listView_team_player.setAdapter(br_tweetlist);

							AsyncTask<Void, Void, Void> wait = new AsyncTask<Void, Void, Void>() {

								@Override
								protected void onPostExecute(Void result) {
									// TODO Auto-generated method stub
									super.onPostExecute(result);
									pd.dismiss();

									br_tweetlist.notifyDataSetChanged();
								}

								@Override
								protected void onPreExecute() {
									pd = ProgressDialog.show(context, "",
											"Loading...", true);
									super.onPreExecute();
								}

								@Override
								protected Void doInBackground(Void... params) {

									String tweetlistjson = Utils
											.readJsonFeed(
													"http://sportizza.com/interface/ios_twitter_api.php?player_code="
															+ br_tweet_str[0]
															+ "&champ_code=-1&sport_code="
															+ br_tweet_str[2]
															+ "", context);

									if (tweetlistjson == null
											|| tweetlistjson.equals("null")) {

										Thread thread1 = new Thread(
												new Runnable() {
													public void run() {

														try {
														} catch (Exception e) {
															e.printStackTrace();
														}
														context.runOnUiThread(new Runnable() {
															public void run() {
																final Custom_dialog_class custom_dialog = new Custom_dialog_class(
																		context,
																		"check_back",
																		true,
																		null,
																		true);
																custom_dialog
																		.show();

																final Timer t = new Timer();
																t.schedule(
																		new TimerTask() {
																			public void run() {
																				custom_dialog
																						.dismiss();
																				t.cancel();
																			}
																		}, 2000);
															}
														});
													}
												});

										thread1.start();
										return null;
									} else {

										try {
											JSONArray array_tweet = new JSONArray(
													tweetlistjson);

											int array_len = array_tweet
													.length();

											int count = 0;
											for (int i = 0; i < array_len; i++) {

												JSONObject JsonObject_sport = array_tweet
														.getJSONObject(i);

												String ss_screen_name = JsonObject_sport
														.getString("ss_screen_name");

												String ss_tw = JsonObject_sport
														.getString("ss_tw");

												String ss_tweet_url = JsonObject_sport
														.getString("ss_tweet_url");

												String ss_profile_url = JsonObject_sport
														.getString("ss_profile_url");

												tweet_info.add(ss_screen_name
														+ "''" + ss_tweet_url
														+ "''" + ss_profile_url
														+ "''" + ss_tw);

												tweet_details
														.put(ss_tw,
																ss_screen_name
																		+ "''"
																		+ ss_tweet_url
																		+ "''"
																		+ ss_profile_url
																		+ "''"
																		+ ss_tw);
											}

										} catch (Exception e) {
										}

										Log.w("suraj_", "tweet_info = "
												+ tweet_info);

										// lv.setAdapter(null);

									}

									return null;
								}

							};

							wait.execute();

							listView_team_player
									.setOnItemClickListener(new OnItemClickListener() {

										@Override
										public void onItemClick(
												AdapterView<?> parent, View v,
												int position, long id) {

											Log.d("suraj_", "Click On = "
													+ tweet_info.get(position));

											String[] url = tweet_info
													.get(position).toString()
													.split("''");

											Log.d("suraj_", "url[1]==" + url[1]);

											String urls = null;
											if (url[1] == null
													|| url[1].equals("")) {
												urls = url[3].substring(url[3]
														.lastIndexOf("http://"));
												// Log.d("suraj_","URL11 = "+url[3].substring(url[3].lastIndexOf("http://")));
											} else {
												urls = url[1];
											}

											Log.d("suraj_", "URL = " + urls);

											Uri uriUrl = Uri.parse(urls);
											Intent launchBrowser = new Intent(
													Intent.ACTION_VIEW, uriUrl);
											context.startActivity(launchBrowser);
										}
									});

							popupWindow.showAtLocation(viewHolder.br_set_team_tweet,
									Gravity.NO_GRAVITY, 0, 0);
						}

					}
				});

				int[] location = new int[2];
				viewHolder.br_set_team_tweet.getLocationOnScreen(location);

				Rect anchorRect = new Rect(location[0], location[1],
						location[0] + viewHolder.br_set_team_tweet.getWidth(), location[1]
								+ viewHolder.br_set_team_tweet.getHeight());

				viewHolder.br_set_team_tweet.measure(LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT);

				int rootWidth = viewHolder.br_set_team_tweet.getMeasuredWidth();
				int rootHeight = viewHolder.br_set_team_tweet.getMeasuredHeight();

				int screenWidth = mWindowManager.getDefaultDisplay().getWidth();

				int xPos = screenWidth - rootWidth + 0;
				int yPos = anchorRect.top - rootHeight + 0;

				if (rootWidth > anchorRect.right - anchorRect.left) {
					// right
					xPos = anchorRect.right - rootWidth;
				} else {
					// left
					xPos = anchorRect.left + 15;
				}

				if (xPos + rootWidth > screenWidth)
					xPos = screenWidth - rootWidth - 20;

				// display on bottom
				if (rootHeight > anchorRect.top) {
					yPos = anchorRect.bottom + 0;
					// mPopupWindow.setAnimationStyle(R.style.Animations_GrowFromTop);
				}

				if (position == player_adp.size() - 1) {
					popupWindow.showAtLocation(viewHolder.br_set_team_tweet,
							Gravity.NO_GRAVITY, xPos, yPos - 10);
				} else {
					popupWindow.showAtLocation(viewHolder.br_set_team_tweet,
							Gravity.NO_GRAVITY, xPos, yPos + 110);
				}
			}
		});
		

		
		if (MainActivity.playerAll != null) {
			if (MainActivity.playerAll.contains(viewHolder.br_set_team_follow.getTag()
					.toString()) == true) {
				viewHolder.br_set_team_follow.setText("UNFOLLOW");
			} else {
				viewHolder.br_set_team_follow.setText("FOLLOW");
			}

		}
		
		return convertView;
	}

	public int getImgLoader(String sport_code) {

		int loader = R.drawable.gam;

		if (sport_code.equalsIgnoreCase("AFT")) {
			loader = R.drawable.aft;
		} else if (sport_code.equalsIgnoreCase("TT")) {
			loader = R.drawable.tt;
		} else if (sport_code.equalsIgnoreCase("POL")) {
			loader = R.drawable.pol;
		} else if (sport_code.equalsIgnoreCase("SWI")) {
			loader = R.drawable.swi;
		} else if (sport_code.equalsIgnoreCase("UFC")) {
			loader = R.drawable.ufc;
		} else if (sport_code.equalsIgnoreCase("BAD")) {
			loader = R.drawable.bad;
		} else if (sport_code.equalsIgnoreCase("BB")) {
			loader = R.drawable.bb;
		} else if (sport_code.equalsIgnoreCase("CRI")) {
			loader = R.drawable.cri;
		} else if (sport_code.equalsIgnoreCase("F1")) {
			loader = R.drawable.f1;
		} else if (sport_code.equalsIgnoreCase("GAM")) {
			loader = R.drawable.gam;
		} else if (sport_code.equalsIgnoreCase("GOL")) {
			loader = R.drawable.gol;
		} else if (sport_code.equalsIgnoreCase("HOC")) {
			loader = R.drawable.hoc;
		} else if (sport_code.equalsIgnoreCase("ICE")) {
			loader = R.drawable.ice;
		} else if (sport_code.equalsIgnoreCase("IND")) {
			loader = R.drawable.ind;
		} else if (sport_code.equalsIgnoreCase("MGP")) {
			loader = R.drawable.mgp;
		} else if (sport_code.equalsIgnoreCase("NAS")) {
			loader = R.drawable.nas;
		} else if (sport_code.equalsIgnoreCase("OLY")) {
			loader = R.drawable.oly;
		} else if (sport_code.equalsIgnoreCase("RUG")) {
			loader = R.drawable.rug;
		} else if (sport_code.equalsIgnoreCase("SBK")) {
			loader = R.drawable.sbk;
		} else if (sport_code.equalsIgnoreCase("SOC")) {
			loader = R.drawable.soc;
		} else if (sport_code.equalsIgnoreCase("SPO")) {
			loader = R.drawable.spo;
		} else if (sport_code.equalsIgnoreCase("SQU")) {
			loader = R.drawable.squ;
		} else if (sport_code.equalsIgnoreCase("TEN")) {
			loader = R.drawable.ten;
		} else if (sport_code.equalsIgnoreCase("V8C")) {
			loader = R.drawable.v8c;
		} else if (sport_code.equalsIgnoreCase("WRC")) {
			loader = R.drawable.wrc;
		} else {
			loader = R.drawable.gam;
		}
		return loader;
	}
	
}
